package com.gadgets.framework.common.util;

import com.gadgets.framework.common.constant.GadgetsExceptionConstant;
import com.gadgets.framework.common.exception.GadgetsException;
import com.gadgets.framework.common.exception.GadgetsServiceException;
import com.gadgets.framework.common.exception.GadgetsValidateException;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;

public class ExcelImportUtil {

    public static final String EXCEL_2003_SUFFIX = "xls";

    public static final String EXCEL_2007_SUFFIX = "xlsx";

    public static final String M_EXCEL_2007_SUFFIX = "xlsm";

    public static Workbook getExcelFile(File file, String suffix) throws GadgetsException{
        try {
            FileInputStream inputStream = new FileInputStream(file);
            Workbook workbook = null;
            if(EXCEL_2007_SUFFIX.equals(suffix) || M_EXCEL_2007_SUFFIX.equals(suffix)){
                workbook = new XSSFWorkbook(inputStream);
            }else if(EXCEL_2003_SUFFIX.equals(suffix)){
                workbook = new XSSFWorkbook(inputStream);
            }else{
                throw new GadgetsValidateException(GadgetsExceptionConstant.VALIDATE_ERROR,"文件后缀类型错误");
            }
            return workbook;
        } catch (FileNotFoundException e) {
            throw new GadgetsServiceException(GadgetsExceptionConstant.VALIDATE_ERROR,"文件不存在");
        } catch (IOException e) {
            throw new GadgetsServiceException(GadgetsExceptionConstant.VALIDATE_ERROR,"文件I/O读取失败");
        }
    }

}
